package com.example.computer_component_manager.volley

import com.android.volley.NetworkResponse
import com.android.volley.Response
import com.android.volley.toolbox.HttpHeaderParser
import com.android.volley.toolbox.JsonObjectRequest
import org.json.JSONObject
import java.nio.charset.Charset

/**
 * 自定义JsonObjectRequest类
 *
 * @author 1923111015董寺卓
 */

class MyJsonObjectRequest(
    method: Int,
    url: String?,
    jsonRequest: JSONObject?,
    listener: Response.Listener<JSONObject>?,
    errorListener: Response.ErrorListener?,
) : JsonObjectRequest(method, url, jsonRequest, listener, errorListener) {

    /**
     * 重写网络响应方法，如果response出现Set-Cookie字段，则存入haredPreferences
     */
    override fun parseNetworkResponse(response: NetworkResponse): Response<JSONObject> {
        // 检查本地是否存在session，如无，则保存session到本地
        VolleyApplication.instance.checkSessionCookie(response.headers!!)
        val jsonObject = JSONObject(String(response.data,
            Charset.forName(HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET))))
        return Response.success(jsonObject, HttpHeaderParser.parseCacheHeaders(response))
    }

    /**
     * 重写头，在每次请求之前，头就会添加JSESSIONID信息，以持续会话
     */
    override fun getHeaders(): MutableMap<String, String> {
        var headers = super.getHeaders()
        headers = VolleyApplication.instance.addSessionCookie(headers)
        return headers
    }
}